#include "includes.h"

#ifdef USE_I2C

i2c_t I2c;

void I2cSlaInit(void)
{
	uint8_t i;
	
	for(i=0;i<TXBUF_LEN;i++)
	{
		I2c.txbuf[i] = i+1;
	}
	I2CADR = SLAVE_ADDR;
	I2CCON = 0x44;								//Enable I2C bus, ACK
	IE1 |= BIT0;									//Enable I2C interrupt
}


uint8_t I2cWrFifo(uint8_t dev, uint8_t *dat, uint8_t len)
{
	uint8_t i;
	
	I2CCON = 0x60;								//Start
	while(!(I2CCON&BIT3));
	I2CDAT = dev;									//Send devivce address
	I2CCON = 0x40;
	while(!(I2CCON&BIT3));
	if(I2CSTA!=0x18)
		return 1;
	
	for(i=0;i<len;i++)
	{
		I2CDAT = *dat++;
		if(i<(len-1))
		{
			I2CCON = 0x44;
			while(!(I2CCON&BIT3));
			if(I2CSTA!=0x28)
				return 1;
		}
		else
		{
			I2CCON = 0x40;
			while(!(I2CCON&BIT3));
		}
	}
	I2CCON = 0x50;								//Stop
	return 0;
}

uint8_t I2cRdFifo(uint8_t dev, uint8_t *dat, uint8_t len)
{
	uint8_t i;
	
	I2CCON = 0x60;								//Start
	while(!(I2CCON&BIT3));
	I2CDAT = dev|0x01;						//Send device address
	I2CCON = 0x40;
	while(!(I2CCON&BIT3));
	if(I2CSTA!=0x40)
		return 1;
	for(i=0;i<len;i++)
	{
		if(i<(len-1))
			I2CCON = 0x44;
		else
			I2CCON = 0x40;
		while(!(I2CCON&BIT3));			//Read data
		*dat++ = I2CDAT;
	}
	I2CCON = 0x50;								//Stop
	return 0;
}


#ifdef USE_I2C_DEMO
uint8_t I2cBuf[5]={0x11,0x22,0x33,0x44};
#define I2C_MASTER
//#define I2C_SLAVER
void I2cDemo(void)
{
#ifdef I2C_SLAVER
	I2cSlaInit();
	EA = 1;
#endif	//I2C_SLAVER
	while(1)
	{
#ifdef I2C_MASTER
		DelayMs(500);
		I2cWrFifo(SLAVE_ADDR, I2cBuf, 3);
		DelayMs(500);
		I2cRdFifo(SLAVE_ADDR, I2c.rxbuf, 3);
		LED0 = ~LED0;
#endif	//I2C_MASTER
	}
}
#endif	//USE_I2C_DEMO


#endif	//USE_I2C

